﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using ClickNET.Imaging;
using ClickNET.IO;

namespace ClickNET.Imaging
{
    [XmlRoot()]
    public class Gallery
    {
        static readonly object padlock = new object();

        public Gallery() { }

        public Gallery(string galleryFolder)
        {
            this.FolderName = galleryFolder;
            this.Title = galleryFolder;
            this.Description = string.Empty;
        }

        public void ProcessGalleryFolder()
        {
            lock (padlock)
            {
                this.Pictures = new List<Picture>();

                string imageDirFullPath = Path.Combine(Config.DataDirectory, s_imageDirectory);
                string galleryFullPath = Path.Combine(imageDirFullPath, this.FolderName);
                string galleryXmlPath = FileSystemGalleryManager.GetGalleryXmlFilePath(this.FolderName);

                DirectoryProcessor d = new DirectoryProcessor(galleryFullPath);
                d.ProcessFile += new DirectoryProcessor.ProcessFileDelegate(ProcessSingleFile);
                d.Process();

                ClickNET.Serialization.SerializationManager.Xml.ObjectToXMLFile(this, galleryXmlPath);
            }
        }

        private void ProcessSingleFile(string fileLocation)
        {
            if (Picture.FileNameHasAllowedExtension(fileLocation))
            {
                Picture p = new Picture(fileLocation, this.FolderName);
                p.CreateThumbnails();
                this.Pictures.Add(p);
            }
        }

        public Picture GetFirstPicture()
        {
            if (this.Pictures.Count > 0)
                return this.Pictures[0];

            return null;
        }

        [XmlElement()]
        public string Title { get; set; }

        [XmlElement()]
        public string Description { get; set; }

        [XmlElement()]
        public string FolderName { get; set; }

        [XmlArray()]
        public List<Picture> Pictures { get; set; }

        private static readonly string s_imageDirectory = Config.DefaultInstance.GetConfigString("gallery", "imageDirectory");
        private static readonly string s_thumbsDirectory = Config.DefaultInstance.GetConfigString("gallery", "thumbsDirectory");
        private static readonly List<string> s_allowedFileExtensions = Config.DefaultInstance.GetConfigCommaSeparatedString("gallery", "allowedFileExtensions");

    }
}
